package com.rdc.dictionary.daily;


import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.rdc.dictionary.application.App;
import com.rdc.dictionary.bean.DailySentence;
import com.rdc.dictionary.util.ImageAction;
import com.rdc.dictionary.util.NetworkUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author Soul Mate
 * @file 文件名
 * @brief 活动的Model类，用于数据的获取
 */

public class DailyModel
{



	//接收网络获取数据
	private String data;

	//利用回调接口来处理网络请求失败的情况

	private DailyActivityContract.onGetData listener;

	//暂时放置每日一句数据
	private DailySentence dailySentence = new DailySentence();


	public DailySentence getDaily()
	{
		return dailySentence;
	}


		public void setListener(DailyActivityContract.onGetData listener) {
			this.listener = listener;
		}


	Handler mHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			//接收获取的数据
			if(msg.what == 1)
			{data =(String) msg.obj;

			//解析数据
			parseJSONWithJSONObject(data);
			}

			//接收bitmap图片
			if(msg.what == 2)
			{
				Bundle b = msg.getData();
				Bitmap bmp = b.getParcelable("picture");
				dailySentence.setImage(bmp);
			}

			listener.onSuccess(dailySentence);

		}
	};





	/**
	 * 网络请求每日一句数据
	 */
	public void sendRequestWithOkHttp()
	{
		//检查网络
		if(NetworkUtil.isMobileDataEnable(App.sContext)) {
			//有网络
			new Thread(new Runnable()
			{
				@Override public void run()
				{
					OkHttpClient client = new OkHttpClient();
					Request request = new Request.Builder().url("http://open.iciba.com/dsapi").build();
					Response response = null;
					try
					{
						response = client.newCall(request).execute();
						String responseData = response.body().string();

						//利用Handler传递数据
						Message msg = new Message();
						msg.obj = responseData;
						msg.what =1;
						mHandler.sendMessage(msg);

						//Json格式
						JSONObject jsonObject = new JSONObject(responseData);

						//传递图片
						Message msg1 = new Message();
						Bundle b = new Bundle();

						//解析网络图片为bitmap
						b.putParcelable("picture",ImageAction.getURLImage(jsonObject.getString("picture2")));
						msg1.setData(b);
						msg1.what = 2;
						mHandler.sendMessage(msg1);

					} catch (IOException | JSONException e)
					{
						e.printStackTrace();
					}
				}
			}).start();

		}else
		{
			//无网络
			listener.onFail();
		}
	}


	//解析JSON数据并保存
	private void parseJSONWithJSONObject(String jsonData ) {
		try {
			JSONObject jsonObject = new JSONObject(jsonData);

			//解析出的数据保存到daily中
			dailySentence.setChinese(jsonObject.getString("note")) ;
			dailySentence.setEnglish(jsonObject.getString("content"));
			dailySentence.setMp3(jsonObject.getString("tts"));


		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
